import { writable, derived } from "svelte/store";
import { object, string, number, type Asserts } from 'yup';
import { getLocalStorage } from "@util/localstorage";

export type User = {
  id: number;
  mock_id: string;
  role: string;
  status: number;
  nickname: string | null;
  avatar: string | null;
  maxium_datasets: number;
};

export const UserSchema = object({
  id: number().required(),
  mock_id: string().required(),
  nickname: string().optional().max(16, "最多16个字"),
  status: number().required(),
  avatar: string().optional(),
})

export const UpdateUserNicknameSchema = UserSchema.pick(["nickname"]);
export const UpdateUserAvatarSchema = UserSchema.pick(["avatar"]);


const defaultAnonymousUser:User = {id: 0, mock_id: "", role: "", status: 0, nickname: null, avatar: null, maxium_datasets: 1}

export const MOCK_ID_KEY = `mock_id@gsc-dataset`;
export const SIGN_IN_FLAG_KEY = `sign_out_flag@gsc-dataset`;

export const mockId$ = writable<string>(getLocalStorage(MOCK_ID_KEY));
export const signInFlag$ = writable<boolean>(!!getLocalStorage(SIGN_IN_FLAG_KEY));

export const user$ = writable<User>(defaultAnonymousUser);

export const isSigned$ = derived([user$, signInFlag$], ([$user$, $signInFlag$], set: (v: boolean) => void) => {
  set($user$ && $user$.status === 1 && $signInFlag$);
});

export const avatarBackup$ = derived(user$, ($user$, set: (v: string) => void) => {
  let baseName = $user$.mock_id.charAt($user$.mock_id.length - 1).toUpperCase()
  if ($user$.nickname) {
    baseName = $user$.nickname.charAt(0).toUpperCase()
  }
  set(baseName);
});